<!--
 * @Author: CZY
 * @Date: 2024-09-10 23:53:28
 * @LastEditors: CZY
 * @LastEditTime: 2024-09-10 23:53:28
 * @Description:
-->

<template>
  <div class="center_bottom">
    <div class="ptz_select">
      <span class="text">云台通道:</span>
      <el-select v-model="dialogForm.channelName" placeholder="请选择" style="margin-left: 5px" size="mini" @change="onChannelChange">
        <el-option
            v-for="item in channelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
    </div>
    <div class="item" v-for="(item,index) in data" :key="index">
      <div class="subItem" v-for="(subItem, subIndex) in Object.entries(item)" :key="subIndex">
        <div class="slaveAddress" v-cloak>
          <div>云台信道:{{subItem[0].split('-')[1]}}</div>
        </div>
        <div class="angle">
          <div class="pan">
            <!--        水平 -->
            <svg class="iconfont" aria-hidden="true" style="color: #5daf34;margin-right: 5px;">
              <use xlink:href="#icon-shuipingjiaodu"></use>
            </svg>
            <span v-cloak>水平角度<span class="number">&nbsp;{{getPanAngle(subItem[1])}}</span></span>
          </div>
          <div class="tilt">
            <!--        垂直 -->
            <svg class="iconfont" aria-hidden="true" style="color: orangered;margin-right: 5px;">
              <use xlink:href="#icon-chuizhijiaodu"></use>
            </svg>
            <span v-cloak>垂直角度<span class="number">&nbsp;{{getTiltAngle(subItem[1])}}</span></span>
          </div>
        </div>
        <div class="btn">
          <el-button size="mini" type="primary" icon="el-icon-edit" circle @click="openDialog(item)"></el-button>
        </div>
      </div>
    </div>

    <el-dialog
        title="角度设置"
        :visible.sync="dialogVisible"
        width="30%"
        append-to-body
        :before-close="handleClose">
      <div>
        <el-form label-position="right" :rules="rules" label-width="100px" :model="dialogForm" ref="leftTopRuleForm">
          <el-form-item label="通道:" prop="channelName">
            <el-input v-model="dialogForm.channelName" placeholder="请输入" disabled/>
          </el-form-item>
          <el-form-item label="信道:" prop="address">
            <el-select v-model="dialogForm.address" placeholder="请选择" disabled>
              <el-option
                  v-for="item in addressOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="几何:" prop="direction">
            <el-select v-model="dialogForm.direction" placeholder="请选择">
              <el-option
                  v-for="item in directionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角度:" prop="angle">
            <el-input v-model="dialogForm.angle" :min="-360" :max="360" placeholder="请输入角度" type="number"></el-input>
          </el-form-item>
          <el-form-item>

          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('leftTopRuleForm')">
              立即发送
            </el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import axios from "axios";
import CountTo from 'vue-count-to'

export default {
  components: {
    CountTo,
  },
  data() {
    return {
      channelOptions: [],
      timer: null,
      data:null,
      dialogVisible:false,
      dialogForm:{
        address:null,
        direction:null,
        angle:null,
        channelName:'0000000000000000'
      },
      directionOptions:[{label:'PAN',value:'PAN'},{label:'TILT',value:'TILT'}],
      addressOptions:[],
      rules: {
        address: [
          {required: true, message: '请选择', trigger: 'blur'},
        ],
        direction: [
          {required: true, message: '请选择', trigger: 'blur'}
        ],
        angle: [
          {required: true, message: '请输入', trigger: 'blur'}
        ],
      }
    }
  },
  mounted() {
    this.timer = setInterval(()=>{
      this.getData(false);
    },3000)
  },
  created() {
    this.getData(true);
  },
  beforeDestroy() {
    this.clearData();
  },
  methods: {
    //获取角度数据
    async getData(first) {
      let channelNameArray = [];
      const res = await axios.get(`${process.env.VUE_APP_HOST}/ptz/list`);
      if(Object.keys(res).length === 0){
        // 192.168.2.100 - 通道0000000000000000, 地址码30
        axios.get(`${process.env.VUE_APP_HOST}/ptz/getAngleValue?slaveAddress=30&direction=PAN&channelName=0000000000000000`);
        axios.get(`${process.env.VUE_APP_HOST}/ptz/getAngleValue?slaveAddress=30&direction=TILT&channelName=0000000000000000`);

        // 192.168.32.100 - 通道0000000000000001, 地址码20
        axios.get(`${process.env.VUE_APP_HOST}/ptz/getAngleValue?slaveAddress=20&direction=PAN&channelName=0000000000000001`);
        axios.get(`${process.env.VUE_APP_HOST}/ptz/getAngleValue?slaveAddress=20&direction=TILT&channelName=0000000000000001`);

        // 192.168.30.100 - 通道0000000000000002, 地址码20
        axios.get(`${process.env.VUE_APP_HOST}/ptz/getAngleValue?slaveAddress=20&direction=PAN&channelName=0000000000000002`);
        axios.get(`${process.env.VUE_APP_HOST}/ptz/getAngleValue?slaveAddress=20&direction=TILT&channelName=0000000000000002`);
        return;
      }
      // 将数据转换为数组并排序
      const sortedArray = Object.entries(res).sort((a, b) => {
        // 提取角度和类型
        const [aAngle, aType] = a[0].split('-');
        const [bAngle, bType] = b[0].split('-');

        // 先按照角度排序
        if (aAngle !== bAngle) {
          return aAngle - bAngle;
        }
        // 角度相同，按照类型排序，PAN在前，TILT在后
        return aType.localeCompare(bType);
      });

      // 将相同数字的项合并在一起
      const groupedArray = [];
      let currentNumber = null;
      sortedArray.forEach(([key, value]) => {
        const [channelName, number, type] = key.split('-');
        if(channelName == this.dialogForm.channelName){
          if (currentNumber !== number) {
            currentNumber = number;
            groupedArray.push({ [channelName+'-'+number]: [[type, value]] });
          } else {
            groupedArray[groupedArray.length - 1][channelName+'-'+number].push([type, value]);
          }
        }
        channelNameArray.push(channelName)
      });

      this.addressOptions = []
      groupedArray.forEach(item=>{
        this.addressOptions.push({
          label:Object.keys(item)[0].split("-")[1],
          value:Object.keys(item)[0].split("-")[1]
        })
      })

      if(first){
        this.data = groupedArray;
      }else{
        const newDataString = JSON.stringify(this.data);
        const oldDataString = JSON.stringify(groupedArray);
        // console.log(newDataString,"                  ",oldDataString)
        if (newDataString !== oldDataString) {
          //防止屏闪
          this.data = groupedArray;
          console.log('数据发生了变化');
        }
      }

      // 初始化所有已知通道选项（无论设备是否通电）
      if(this.channelOptions.length == 0){
        // 预定义所有已知通道
        const predefinedChannels = [
          '0000000000000000', // 192.168.2.100
          '0000000000000001', // 192.168.32.100
          '0000000000000002'  // 192.168.30.100
        ];

        // 添加预定义通道
        predefinedChannels.forEach(channel => {
          this.channelOptions.push({
            label: channel,
            value: channel
          });
        });

        // 添加从数据中发现的新通道（如果有的话）
        const uniqueArr = [...new Set(channelNameArray)];
        uniqueArr.forEach(item => {
          // 只添加不在预定义列表中的通道
          if (!predefinedChannels.includes(item)) {
            this.channelOptions.push({label:item,value:item})
          }
        });

        // 设置默认选择通道（优先选择有数据的通道）
        if(uniqueArr.includes('0000000000000002')){
          this.dialogForm.channelName = '0000000000000002';
        } else if(uniqueArr.includes('0000000000000000')){
          this.dialogForm.channelName = '0000000000000000';
        } else if(uniqueArr.includes('0000000000000001')){
          this.dialogForm.channelName = '0000000000000001';
        } else {
          // 如果没有数据，默认选择第一个通道
          this.dialogForm.channelName = '0000000000000000';
        }
      }

    },
    // 通道切换事件
    onChannelChange(value) {
      this.dialogForm.channelName = value;
      this.getData(true); // 重新获取数据
    },
    clearData(){
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    handleClose(){
      this.dialogForm.address = null;
      this.dialogForm.direction = null;
      this.dialogForm.angle = null;
      this.dialogVisible = false
    },
    openDialog(val){
      this.dialogForm.address = Object.keys(val)[0].split("-")[1];
      this.dialogVisible = true;
    },
    submitForm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.dialogForm.angle <= 360 && this.dialogForm.angle >= -360){
            const param = {
              address:this.dialogForm.address,
              direction:this.dialogForm.direction,
              angle:this.dialogForm.angle,
              channelName:this.dialogForm.channelName
            }
            axios.post(`${process.env.VUE_APP_HOST}/ptz/sendSpinCmd`, param);
            this.$message.success("发送成功！")
          }else{
            this.$message.error("角度错误")
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 获取PAN角度（水平角度）
    getPanAngle(angleArray) {
      if (!angleArray || angleArray.length === 0) return 0;
      const panItem = angleArray.find(item => item[0] === 'PAN');
      return panItem ? panItem[1] : 0;
    },
    // 获取TILT角度（垂直角度）
    getTiltAngle(angleArray) {
      if (!angleArray || angleArray.length === 0) return 0;
      const tiltItem = angleArray.find(item => item[0] === 'TILT');
      return tiltItem ? tiltItem[1] : 0;
    }
  },
}
</script>

<style>
[v-cloak]{
  display: none;
}
</style>

<style scoped lang="scss">
.center_bottom {
  width: 100%;
  height: 100%;
  overflow-y: auto;

  .ptz_select{
    display: flex;
    justify-content: center;
    .text{
      display: flex;
      align-items: center;
    }
  }
  .item{
    display: flex;
    width: 100%;
    height: 65px;
    //background-image: url("../../../../public/img/bg-title.png");
    background-image: url("/img/bg-title.png");
    background-size: 100% 100%;
    margin: 10px 0 10px 0;
    .subItem{
      display: flex;
      width: 100%;
      padding-left: 20px;

      .slaveAddress{
        display: flex;
        align-items: center;
        padding-top: 4px;
        font-size: 22px;
        font-family: MyCustomFont,sans-serif;
        width: 150px;
      }

      .angle{
        display: flex;
        flex-direction: column;
        justify-content: space-evenly;
        padding-top: 9px;
        padding-left: 30px;
        width: 200px;

        .number{
          font-family: MyCustomFont,sans-serif;
        }

        .pan{

        }
        .tilt{

        }

        .pan,.tilt{
          width: 100%;
          .iconfont{
            font-size: 20px;
          }
        }
      }

      .btn{
        display: flex;
        align-items: center;
      }
    }
  }
}

@font-face {
  font-family: 'MyCustomFont';
  src: url('/font/ysbt.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}
</style>
